package com.jxmcloud.business.cut.service.impl.app.activity;

import cn.hutool.core.util.ObjectUtil;
import com.jxmcloud.business.ce.service.CeSysParameterService;
import com.jxmcloud.business.cut.constants.CutConstants;
import com.jxmcloud.business.cut.constants.CutErrorMsg;
import com.jxmcloud.business.cut.dto.client.*;
import com.jxmcloud.business.cut.dtoCommon.BagInfoDto;
import com.jxmcloud.business.cut.dtoCommon.InviteSuccessListDto;
import com.jxmcloud.business.cut.dtoCommon.UserInfoDto;
import com.jxmcloud.business.cut.handler.UserEncryptionHandler;
import com.jxmcloud.business.cut.json.DataConfigService;
import com.jxmcloud.business.cut.model.database.DBUserInviteSuccess;
import com.jxmcloud.business.cut.service.app.activity.IInviteSuccessService;
import com.jxmcloud.business.cut.service.database.IUserInviteSuccessDBService;
import com.jxmcloud.business.cut.service.user.IUserActivityService;
import com.jxmcloud.business.cut.service.user.IUserBagService;
import com.jxmcloud.business.cut.service.user.IUserFlowService;
import com.jxmcloud.business.cut.util.MyTool;
import com.jxmcloud.business.cut.vo.client.*;
import com.jxmcloud.business.cut.vo.json.ConfigGlobalGlobalVo;
import com.jxmcloud.business.cut.vo.json.ConfigStartVo;
import com.jxmcloud.business.cut.vo.user.PlayerInfoVo;
import com.xlcloud.platform.api.exception.BusinessException;
import com.xlcloud.platform.util.DateUtil;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Service
public class InviteSuccessServiceImpl implements IInviteSuccessService {
    @Resource
    private IInviteSuccessService inviteSuccessDBService;
    @Resource
    private IUserActivityService userActivityService;
    @Autowired
    private CeSysParameterService sysParameterService;
    @Resource
    private IUserInviteSuccessDBService userInviteSuccessDBService;
    @Resource
    private DataConfigService dataConfigService;
    @Resource
    private IUserBagService userBagService;
    @Resource
    private IUserFlowService userFlowService;


    @Override
    public FreshReceivedInviteVo freshReceivedInvite(FreshReceivedInviteDto dto, PlayerInfoVo player) {
        String error = CutErrorMsg.ERROR_TRUE;
        FreshReceivedInviteVo result = new FreshReceivedInviteVo();
        do {
            // 清空通知
            userActivityService.removeAllNoticeType(player);
        } while (false);
        if (!error.equals(CutErrorMsg.ERROR_TRUE)) {
            // 抛出异常
            throw new BusinessException(error);
        }
        return result;
    }

    @Override
    public GainDrawValueAwardVo gainDrawValueAward(GainDrawValueAwardDto dto, PlayerInfoVo player) {
        String error = CutErrorMsg.ERROR_TRUE;
        GainDrawValueAwardVo result = new GainDrawValueAwardVo();
        do {
            ConfigGlobalGlobalVo configGlobalGlobalConfig = dataConfigService.getConfigGlobalGlobalConfig();
            if (ObjectUtil.isNull(configGlobalGlobalConfig)) {
                error = "服务器配置错误";
                break;
            }
            // 提现总值
            Integer totalDrawValue = configGlobalGlobalConfig.getCashCoinMax();
            if (!MyTool.isTure(totalDrawValue)) {
                error = "服务器配置错误~";
                break;
            }
            // 提现值道具id
            Integer cashCoinItemId = configGlobalGlobalConfig.getItemIdCashCoin();
            if (!MyTool.isTure(cashCoinItemId)) {
                error = "服务器配置错误~~";
                break;
            }
            // 直播流程id
            ConfigStartVo configStart = dataConfigService.getConfigStartConfig(player.getActivity().getStartId());
            if (ObjectUtil.isNull(configStart)) {
                error = "服务器配置错误~~~";
                break;
            }
            Integer liveStepId = configStart.getNewersFitEnterLiveStep();
            if (!MyTool.isTure(liveStepId)) {
                error = "服务器配置错误~~~~";
                break;
            }

            Integer uid = player.getBase().getUid();
            Integer activityId = player.getActivity().getActivityId();
            // 所有可领取新人列表
            List<DBUserInviteSuccess> canGainAwardList = Lists.newArrayList();
            // 总新人邀请列表
            List<DBUserInviteSuccess> allNewerList = userInviteSuccessDBService.selectInviteNewersList(uid, activityId);
            for (DBUserInviteSuccess newer : allNewerList) {
                if (newer.getIsGainAward().equals(0)) {
                    canGainAwardList.add(newer);
                }
            }
            // 上次已邀请新人数
            int lastInviteNewerCount = allNewerList.size() - canGainAwardList.size();
            // 上次剩余还需新人邀请数
            int lastLeftInviteCount = userActivityService.calLeftNeedNewerCount(player, lastInviteNewerCount);

            // 领取
            int gainTotalCount = 0;
            List<InviteSuccessListDto> inviteSuccessList = Lists.newArrayList();
            for (DBUserInviteSuccess canGainAward : canGainAwardList) {
                // 当前提现值
                Integer curCount = userBagService.getItemCount(player, cashCoinItemId);
                // 剩余提现值
                int leftCount = totalDrawValue - curCount;
                if (leftCount > 0 && lastLeftInviteCount > 0) {
                    // 本次获得数量
                    int gainCount = leftCount / lastLeftInviteCount;

                    // 加道具
                    gainTotalCount += gainCount;
                    userBagService.addItem(player, cashCoinItemId, gainCount);
                }

                // 标记已领取
                userInviteSuccessDBService.updateGainAward(canGainAward.getId());

                lastLeftInviteCount--;

                // 助力记录
                InviteSuccessListDto awardVo = new InviteSuccessListDto();
                awardVo.setXlId(canGainAward.getInvitedXlId().intValue());
                awardVo.setAccount(canGainAward.getInvitedAccount());
                awardVo.setName(canGainAward.getInvitedName());
                awardVo.setIcon(canGainAward.getInvitedIcon());
                Long respTime = DateUtil.dateToTime(canGainAward.getRespTime());
                awardVo.setTime(respTime.intValue());
                inviteSuccessList.add(awardVo);
            }

            // 判断全部完成, 进入直播流程
            if (lastLeftInviteCount <= 0) {
                userFlowService.enterNextProgress(player, liveStepId);
                result.setNextStep(liveStepId);
            }

            // 回包
            BagInfoDto award = new BagInfoDto();
            award.setId(cashCoinItemId);
            award.setCount(gainTotalCount);
            result.setAward(award);
            result.setInviteSuccessList(inviteSuccessList);

        } while (false);
        if (!error.equals(CutErrorMsg.ERROR_TRUE)) {
            // 抛出异常
            throw new BusinessException(error);
        }
        return result;
    }

    @Override
    public GetInviteAwardVo getInviteAward(GetInviteAwardDto dto, PlayerInfoVo player) {
        String error = CutErrorMsg.ERROR_TRUE;
        GetInviteAwardVo result = new GetInviteAwardVo();
        do {
            GetInviteAwardVo gainResult = userActivityService.getInviteSuccessAward(player);
            if (ObjectUtil.isNull(gainResult)) {
                error = "奖励领取失败";
                break;
            }
            result = gainResult;
        } while (false);
        if (!error.equals(CutErrorMsg.ERROR_TRUE)) {
            // 抛出异常
            throw new BusinessException(error);
        }
        return result;
    }

    @Override
    public GetInviteAwardProgressVo getInviteAwardProgress(GetInviteAwardProgressDto dto, PlayerInfoVo player) {
        String error = CutErrorMsg.ERROR_FALSE;
        GetInviteAwardProgressVo result = new GetInviteAwardProgressVo();
        do {
            GetInviteAwardProgressVo gainResult = userActivityService.getInviteSuccessAwardProgress(player);
            if (ObjectUtil.isNull(gainResult)) {
                break;
            }
            result = gainResult;
            error = CutErrorMsg.ERROR_TRUE;
        } while (false);
        if (!error.equals(CutErrorMsg.ERROR_TRUE)) {
            // 抛出异常
            throw new BusinessException(error);
        }
        return result;
    }

    @Override
    public GetInviteShareUrlVo getInviteShareUrl(GetInviteShareUrlDto dto, PlayerInfoVo player) {
        String error = CutErrorMsg.ERROR_TRUE;
        GetInviteShareUrlVo result = new GetInviteShareUrlVo();
        do {
            // 邀请码
            try {
                Long uid = player.getBase().getUid().longValue();
                Long activityId = player.getActivity().getActivityId().longValue();
                String desInviteCode = UserEncryptionHandler.generateInviteCode(uid, activityId);
                result.setInviteCode(desInviteCode);

                String url = this.sysParameterService.getParamByKeyCache(CutConstants.SHARE_URL).getParameterValue();
                result.setShareUrl(url);
            } catch (UnsupportedEncodingException e) {
                error = "邀请码生成失败";
                break;
            }

        } while (false);
        if (!error.equals(CutErrorMsg.ERROR_TRUE)) {
            // 抛出异常
            throw new BusinessException(error);
        }
        return result;
    }

    @Override
    public InvitedNewersListVo invitedNewersList(InvitedNewersListDto dto, PlayerInfoVo player) {
        String error = CutErrorMsg.ERROR_TRUE;
        InvitedNewersListVo result = new InvitedNewersListVo();
        do {
            Integer uid = player.getBase().getUid();
            Integer activityId = player.getActivity().getActivityId();

            // 邀请新人列表
            List<DBUserInviteSuccess> daoList = userInviteSuccessDBService.selectInviteNewersList(uid, activityId);

            // 已邀请新人数
            int inviteNewerCount = daoList.size();
            // 剩余邀请数
            int leftInviteCount = userActivityService.calLeftNeedNewerCount(player, inviteNewerCount);
            if (leftInviteCount < 0) {
                error = "服务器配置错误";
                break;
            }

            // 回包
            List<UserInfoDto> newersList = Lists.newArrayList();
            for (DBUserInviteSuccess dao : daoList) {
                UserInfoDto newer = new UserInfoDto();
                newer.setAccount(dao.getInvitedAccount());
                newer.setNickName(dao.getInvitedName());
                newer.setIcon(dao.getInvitedIcon());
                newersList.add(newer);
            }
            result.setNewersList(newersList);
            result.setLeftNeedCount(leftInviteCount);
        } while (false);
        if (!error.equals(CutErrorMsg.ERROR_TRUE)) {
            // 抛出异常
            throw new BusinessException(error);
        }
        return result;
    }

    @Override
    public ShareSuccessVo shareSuccess(ShareSuccessDto dto, PlayerInfoVo player) {
        String error = CutErrorMsg.ERROR_TRUE;
        ShareSuccessVo result = new ShareSuccessVo();
        do {
            userActivityService.addShareCount(player, 1);
        } while (false);
        if (!error.equals(CutErrorMsg.ERROR_TRUE)) {
            // 抛出异常
            throw new BusinessException(error);
        }
        return result;
    }

}
